<script setup>
import { tool } from "../tool/index"
import { onMounted, ref, reactive, computed, inject } from "vue"
import Comment from '../components/BlogContent/Comment.vue'
import { ElMessage } from 'element-plus'
import { useRouter } from "vue-router"
// API 地址
const imageUrl = tool.serverPath + "api/app_api/image/download?fileName="
// 初始化数据
const store = inject('store')
const id = ref(store.state.user.id)
const fldBool = ref(false)
const router = useRouter()
const props = defineProps(['BlogId'])
const BlogId = props.BlogId
const content = reactive({ data: {} })
const User = reactive({ data: {} })
const label = ref([])
const Category = ref("")
// 异步请求逻辑
async function fetchData(name, params) {
    try {
        const response = await tool.axiosApi(name, params, "get")
        return response.data[0]
    } catch (error) {

    }
}
// 获取用户信息
async function searchUser() {
    try {
        User.data = await fetchData("user", {
            key: "Search",
            data: {
                key: ["id"],
                value: [content.data.author_id]
            }
        })
        await getFId()
    } catch (error) {

    }
}
// 获取用户是否关注此用户
async function getFId() {
    try {
        const fld = await fetchData("followed", {
            key: "Search",
            data: {
                key: ["user_id", "follows_id"],
                value: [id.value, User.data.id]
            }
        })
        if (fld) {
            fldBool.value = true
        } else {
            fldBool.value = false
        }
    } catch (error) {

    }
}
// 关注用户
async function addFollowed() {
    try {
        if (id.value != User.data.id) {
            const Followed = {
                user_id: id.value,
                follows_id: User.data.id,
                created_at: new Date()
            }
            const data = {
                key: "add",
                data: {
                    key: Object.keys(Followed),
                    value: Object.values(Followed)
                }
            }
            const fld = await tool.axiosApi("followed", data, "post")
            if (fld.message) {
                fldBool.value = true
            } else {
                ElMessage("出错了，请重试")
            }
        } else {
            ElMessage("不能关注自己")
        }
    } catch (error) {

    }

}
// 取消关注
async function desFollowed() {
    try {
        const Followed = {
            user_id: id.value,
            follows_id: User.data.id,
        }


        const data = {
            key: "destroy",
            data: {
                key: Object.keys(Followed),
                value: Object.values(Followed)
            }
        }
        const fld = await tool.axiosApi("followed", data, "post")
        if (fld.message) {
            fldBool.value = false
        } else {
            ElMessage("出错了，请重试")
        }
    } catch (error) {

    }
}
// 获取博客信息
async function searchBlog() {
    try {
        content.data = await fetchData("article", {
            key: "Search",
            data: {
                key: ["id"],
                value: [BlogId]
            }
        })
        if(content.data == undefined){
            alert(
                "该文章不见啦，可能被删除啦"
            )
            router.go(-1)
            window.close();
        }
        for (let i = 1; i <= 5; i++) {
            if (content.data[`label_${i}`]) {
                label.value.push(content.data[`label_${i}`])
            }
        }
        Category.value = (await fetchData("category", {
            key: "Search",
            data: {
                key: ["id"],
                value: [content.data.category]
            }
        }))
        searchUser()
    } catch (error) {

    }
}
// 跳转到标签搜索页
function gotoLabel(value) {
    router.push({ name: `BlogSearch`, params: { type: "label", value: value } })
}
// 跳转分类页面
function GotoCategories(value) {
    const url = router.resolve({ name: 'BlogCategories', params: { id: value } }).href
    window.open(url, '_blank')
}
// 跳转主页页面
function GotoHomePage(value) {
    const url = router.resolve({ name: 'homePage', params: { userID: value } }).href
    window.open(url, '_blank')
}
// 初始化页面
onMounted(async () => {
    await searchBlog()
    window.scrollTo(0, 0)
})

// 图片
const formattedImageUrl = computed(() => imageUrl + User.data.avatar)
const imageArr = ref([])
const hasImage = computed(() =>{
    imageArr.value[0] =imageUrl + content.data.image
    return  imageUrl + content.data.image
} )
</script>

<template>
    <div class="common-layout">
        <el-container>
            <el-aside class="aside">
                <el-affix target=".aside" :offset="69">
                    <div class="card">
                        <el-image v-if="User.data.avatar" fit="cover" :src="formattedImageUrl"></el-image>
                        <el-row>
                            <el-col :span="24">
                                <el-text tag="b" size="large" truncated>{{ User.data.nickname }}</el-text>
                            </el-col>
                            <el-col :span="12">
                                <el-button @click="GotoHomePage(User.data.id)" type="primary ">主页</el-button>
                            </el-col>
                            <el-col :span="12">
                                <el-button v-if="fldBool" type="success " @click="desFollowed()">已关注</el-button>
                                <el-button v-if="!fldBool" type="danger" @click="addFollowed()">关注</el-button>
                            </el-col>
                        </el-row>
                    </div>
                </el-affix>
            </el-aside>
            <el-container>
                <el-header class="header">
                    <h3>《{{ content.data.title }}》
                    </h3>
                    <el-button @click="GotoCategories(Category.id)" type="danger" round>分类：{{ Category.name }}</el-button>
                    <el-button @click="gotoLabel(item)" type="success" v-for="item in label" round># {{ item }}</el-button>
                </el-header>
                <el-main class="main">
                    <el-image v-if="content.data.image" fit="cover" :preview-src-list="imageArr"  :src="hasImage"></el-image>
                    <el-divider />
                    <el-text style="white-space: pre-wrap;color: black;">{{ content.data.content }}</el-text>
                    <div style="text-align: right;">
                        <span><el-text size="small">最后更新日期：{{ content.data.updated_at }}</el-text></span>
                        <el-divider direction="vertical" />
                        <span><el-text size="small">发布日期：{{ content.data.created_at }}</el-text></span>
                    </div>
                </el-main>

                <el-footer class="footer">
                    <Comment :BlogId=content.data.id></Comment>
                </el-footer>
            </el-container>
        </el-container>
    </div>
</template>
  
<style scoped>
.common-layout {
    margin: auto;
    width: 1300px;
    display: flex;
    flex-direction: column;
    min-height: 100vh;
}

.common-layout .aside {
    background-color: white;
    height: auto;
    margin-right: 10px;
    width: 200px;
}

.common-layout .card {
    padding: 15px;
    background-color: white;
    text-align: center;
}

.common-layout .card .el-image {
    width: 100px;
    height: 100px;
    border-radius: 50%;
}

.common-layout .card .el-col {
    margin-top: 5px;
}

.common-layout .header {
    background-color: white;
    height: 100px;
    line-height: 20px;
    font-size: 20px;
}

.common-layout .main {
    border-radius: 5px;
    background-color: white;
    height: auto;
}

.common-layout .main .el-image {
    border-radius: 15px;
    height: 300px;
    width: 100%;
}

.common-layout .main .el-divider {
    margin: 0;
    margin-top: 5px;
    margin-bottom: 5px;
}

.common-layout .footer {
    background-color: white;
    border-radius: 5px;
    padding: 20px;
    margin-top: 10px;
    height: auto;
}
</style>